# Create your views here.
import logging

import ibm_db
from django.http import HttpResponse
from django.shortcuts import render

from TestApp.models import Sales


def hello(request):
    context = {'hello': 'Hello World!'}
    return render(request, 'hello.html', context)


def addgoods(request):
    pc = Sales(dates="20201004", goods="PC", sales="1000")
    pc.save()
    return HttpResponse("<p>数据添加成功！</p>")

# 数据库查询
def getres(sql):
    one_list=[]
    logging.basicConfig(level=logging.INFO)
    dbinfo = "DATABASE=testdb; HOSTNAME=49.234.187.88; PORT=55000; PROTOCOL=TCPIP; UID=db2inst1; PWD=1qaz@WSX;"
    #sql = sql_info()[1].strip()
    try:
        conn = ibm_db.connect(dbinfo, '', '')
    except Exception as err:
        print("connect failed {}".format(repr(err)))
    else:
        logging.info(sql)
        try:
            stmt = ibm_db.exec_immediate(conn, sql)
            result = ibm_db.fetch_both(stmt)
            while result:
                one_list.append(result[2])
                result = ibm_db.fetch_both(stmt)
            return one_list
        except Exception as err:
            print("stmt failed {}".format(repr(err)))
        finally:
            if ibm_db.active(conn):
                ibm_db.close(conn)
            logging.info("connect success close")

            
def db2test(request):
    res=getres("SELECT * FROM POSP.SALES;")
    return HttpResponse(str(res))

